package manongfanshen.t1_wait_t2;

import com.google.common.base.Stopwatch;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

import static util.ThreadUtil.sleepForMilliSeconds;

/**
 * @author ChangLiang
 * @date 2020/3/18
 */
public class MainV0Test {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 作为类的成员变量
     */
    Thread thread = new Thread() {
        @Override
        public void run() {
            // mock do something
            sleepForMilliSeconds(30_000);
            logger.info("thread A complete");
        }
    };

    @Test
    @DisplayName("Main wait for ThreadA and ThreadB complete")
    public void test(){

        Stopwatch stopwatch = Stopwatch.createStarted();

        thread.start();
        // ensure threadA start
        sleepForMilliSeconds(200);
        try {
            // block here
            // main thread invoke threadA's join method
            // that likes synchronized(threadA.class){threadA.wait())
            // so main thread must wait for threadA.notify()
            // and threadA will call notify() after finishing work
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // mock main do something
        sleepForMilliSeconds(1_000);
        logger.info("main thread finish, elapsed time {} milliseconds",stopwatch.elapsed(TimeUnit.MILLISECONDS));
    }
}
